<?php

namespace app\middleware;

use app\common\Send;
use app\utils\Jwt;
use think\facade\Cache;

use app\exception\TokenException;
class VerifyMiddleware
{
    use Send;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        $authorization = $request->header("Authorization");

        if (!empty($authorization)) {
            //指定文件缓存驱动
            $user =Jwt::decodeToken($authorization,env('jwt.api_secret',''));
            $request->_mid = $user->sub ?? 0;
            $request->_mtoken = $authorization ?? '';
            $request->_invitationCode = $user->invitationCode??'';
        }
        $path = $request->url();

        // 放行特定路径
        if (strpos($path, 'login') !== false
            || strpos($path, 'register') !== false
            || strpos($path, 'code') !== false
            || strpos($path, 'upload') !== false
            || strpos($path, 'forgetPassword') !== false
            || preg_match('/^\/[a-z0-9]+\/api\/task(\?|$)/i', $path)
            || strpos($path, 'taskCategoryAll') !== false
            || strpos($path, 'wechatToken') !== false
            || strpos($path, 'getByMark') !== false
            || strpos($path, 'sysIntro') !== false
            || strpos($path, 'sysConfig') !== false
        ) {
            return $next($request);
        }

        //指定文件缓存驱动
        if(empty($authorization) || !Cache::store('file')->has($authorization))  throw new TokenException("请先登录",409);

        return $next($request);
    }
}
